package com.wolfking.jeesite.freemarker.method;

import com.google.common.collect.Sets;
import com.wolfking.jeesite.config.SsoConfig;
import com.wolfking.jeesite.freemarker.FreemarkerMethod;
import com.wolfking.jeesite.sso.SsoService;
import freemarker.template.SimpleSequence;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;

/**
 * freemarker的权限的标签
 * <p>
 *
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年4月28日下午3:50:30
 * @版权 归wolfking所有
 */
@Slf4j
@FreemarkerMethod("hasPermission")
public class HasPermissionMethod implements TemplateMethodModelEx {
    @Autowired
    private SsoService ssoService;

    @Autowired
    private SsoConfig ssoConfig;

    @Override
    public Object exec(List list) throws TemplateModelException {
        if (ssoConfig.isEnabled()) {
            String code = list.get(0).toString();
            if (list.size() == 1) {
                Set<String> userAuthCodes = ssoService.getUserAuthCodes();
                return userAuthCodes.contains(code);
            } else if (list.size() == 2) {
                SimpleSequence sequence = (SimpleSequence) list.get(1);
                Set<String> codeSet = Sets.newHashSet();
                for (int i = 0; i < sequence.size(); i++) {
                    codeSet.add(sequence.get(i).toString());
                }
                return codeSet.contains(code);
            }
            return false;
        } else {
            return true;
        }
    }
}
